/**
 * 工具函数
 *
 * @author CT
 * @email 994599447@qq.com
 * @date 2017.8.14
 */
'use strict';
import { Toast, } from 'native-base';
// import {FormData} from 'react-native';

const Util = {
    /**
     * http get 请求简单封装
     * @param url 请求的URL
     * @param successCallback 请求成功回调
     * @param failCallback 请求失败回调
     */
    get: (url, successCallback, failCallback) => {
        fetch(url)
            .then((response) => response.text())
            .then((responseText) => {
                let result = JSON.parse(responseText);
                successCallback(result.body, result.code, result.message, result.now);
            })
            .catch((err) => {
                failCallback(err);
            });
    },

    /**
     * http post 请求简单封装
     * @param url 请求的URL
     * @param data post的数据
     * @param successCallback 请求成功回调
     * @param failCallback failCallback 请求失败回调
     */
    post: (url, data, successCallback, failCallback) => {
        let formData = new FormData();
        Object.keys(data).map(function(key) {
            var value = data[key];
            formData.append(key, value);
        });

        let fetchOptions = {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                // 'Content-Type': 'application/json'
                'Content-Type': 'multipart/form-data',
            },
            body: formData
            // body: JSON.stringify(data)
        };

        fetch(url, fetchOptions)
            .then((response) => response.text())
            .then((responseText) => {
                let result = JSON.parse(responseText);
                successCallback(result.body, result.code, result.message, result.now);
            })
            .catch((err) => {
                failCallback(err);
            });
    },

    /**
     * 日志打印
     * @param obj
     */
    log: (obj) => {
        var description = "";
        for(let i in obj){
            let property = obj[i];
            description += i + " = " + property + "\n";
        }
        alert(description);
    },

    //浅画颜色
    shadeColor:(color, percent) => {
        const first = parseInt(color.slice(1), 16);
        const black = first & 0x0000FF;
        const green = first >> 8 & 0x00FF;
        const percentage = percent < 0 ? percent * -1 : percent;
        const red = first >> 16;
        const theme = percent < 0 ? 0 : 255;
        const finalColor = (0x1000000 + (Math.round((theme - red) * percentage) + red) * 0x10000 + (Math.round((theme - green) * percentage) + green) * 0x100 + (Math.round((theme - black) * percentage) + black)).toString(16).slice(1);
    
        return `#${finalColor}`;
    },
    //生成唯一Id:12位
    generateUUID:()=>{
        let d = new Date().getTime();
        let uuid = 'xxxxyyyyxyxy'.replace(/[xy]/g, function(c) {
            let r = (d + Math.random()*16)%16 | 0;
          d = Math.floor(d/16);
          return (c=='x' ? r : (r&0x3|0x8)).toString(16);
        });
        return uuid;
        
    },
    //去日期间隔：天数
    getDateDiff:(startDate,endDate)=>{
        try {
            let startTime = new Date(Date.parse(startDate.replace(/-/g,   "/"))).getTime();     
            let endTime = new Date(Date.parse(endDate.replace(/-/g,   "/"))).getTime();     
            let dates = Math.abs((startTime - endTime))/(1000*60*60*24);     
            return  dates;    
        } catch (error) {
            console.log(error);
        }
    },

    //日期字符串转Date对象
    cnvStringToDate:(strDate)=>{
        try {
            if(strDate == undefined || strDate == '') return ;
            return new Date(strDate.replace(/-/g,"/"));
        } catch (error) {
            console.log(error);
        }
    },
    //根据字符串日期获取星期几，返回中文一二三...
    getWeekDay:(strDate)=>{
        try {
            let day = Util.cnvStringToDate(strDate).getDay();
            switch(day){
                case 1:
                    return '一';
                case 2:
                    return '二';
                case 3:
                    return '三';
                case 4:
                    return '四';
                case 5:
                    return '五';
                case 6:
                    return '六';
                case 6:
                    return '日';
                default: 
                    return '未知';
            }
        } catch (error) {
            console.log(error);
        }
    },
    //弹出框,type:	danger,success,warning
    showToast:(msg,type,duration)=>{
        Toast.show({
            text: msg,
            position: 'bottom',
            type: type?type:success,
            duration: duration?duration:2000
          });
    }
};

// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
// 例子： 
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

export default Util;